/**
 * @page: 子账号管理页面
 * @author: Elvis 
 */

import { useEffect, useState, useMemo } from 'react';
import { queryAccountList, queryRoleList, deleteAccount, changeSupplier } from './service';
import FormRender from '@/components/FormRender';
import OperaBtnRender from '@/components/OperaBtnRender';
import TableRender from '@/components/TableRender';
import EditModal from './component/EditModal.jsx';
import { useResize } from '@/hooks/useResize';
import { getFormItem } from './config/form.js';
import { getColumns } from './config/columns.jsx';
import { message } from 'antd';

const AccountComponent = () => {

  const [data, setData] = useState([]);//表格数据

  const [query, setQuery] = useState({});//查询条件

  const [roleList, setRoleList] = useState([]);//角色列表

  const [visible, setVisible] = useState(false);

  const [item, setItem] = useState({});

  const [pages, setPages] = useState({
    current: 1,
    total: 0,
    pageSize: 10,
  })

  //监听变更
  const { el: headerEl, height: headerHeight } = useResize();

  //初始化请求数据列表
  useEffect(() => {
    handleGetRoleList();
  }, [])

  useEffect(() => {
    getTableList(query);
  }, [query, pages.pageSize, pages.current])

  //获取角色列表
  const handleGetRoleList = async () => {
    const { data, success } = await queryRoleList();
    if (success) {
      const arr = [];
      data.map(v => {
        arr.push({
          value: v.id + '',
          label: v.roleName
        })
      })
      setRoleList(arr);
    }
  }

  //获取员工信息列表
  const getTableList = async () => {
    START_LOADING();
    const { data, success } = await queryAccountList({
      ...query,
      current: pages.current,
      size: pages.pageSize,
    })
    END_LOADING();
    if (success) {
      const { records, total } = data;
      setData(records);
      setPages({
        ...pages,
        total
      });
    }
  }

  //添加/编辑员工
  const handleAddAccount = (type = 2, obj = {}) => {
    if (type == 1) {
      setItem(obj);
      setVisible(true);
    } else {
      setItem({});
      setVisible(true);
    }
  }

  //点击更改拿货员权限
  const handleOpenAuth = async (record) => {
    START_LOADING()
    const res = await changeSupplier({
      userId: record.id,
      changeSupplier: record.changeSupplier ? 0 : 1
    })
    END_LOADING()
    if (res.success) {
      message.success('操作成功！');
      getTableList();
    }
  }

  //点击删除
  const handleDelete = async (record) => {
    START_LOADING()
    const res = await deleteAccount({
      userId: record.id
    })
    END_LOADING()
    if (res.success) {
      message.success('删除成功！');
      getTableList();
    }
  }

  //点击编辑和删除
  const handleOpera = (type, record) => {
    if (type == 'edit') {
      handleAddAccount(1, record);
    } else if(type == 'switch') {
      handleOpenAuth(record);
    } else {
      handleDelete(record);
    }
  }

  //表单数据
  const formArr = useMemo(() => {
    return getFormItem({
      roleId: roleList
    });
  }, [roleList])


  const columns = useMemo(() => {
    return getColumns({ handleOpera })
  }, [])

  //表单渲染组件
  const FormRenderProps = {
    query,
    formArr,
    formConfig: {
      name: 'child-account-manage-form',
      style: { marginBottom: '16px' }
    },
    clickSearch(val) {
			setPages({ 
				...pages,
				current: 1
			});      
      setQuery(val);
    },
    clickReset() {
			setPages({ 
				...pages,
				current: 1
			});    
      setQuery({});
    },
  }

  //表格组件
  const TableRenderProps = {
    data,
    columns,
    style: {
      height: `calc(100vh - ${headerHeight + 224}px)`
    },
    pageConfig: {
      pages,
      handlePageSize(page, size) {
        setPages({
          ...pages,
          current: page,
          pageSize: size
        });
      }
    }
  }

  //编辑员工组件
  const EditModalProps = {
    item,
    roleList,
    handleOk() {
      setVisible(false);
      getTableList();
    },
    handleCancel() {
      setVisible(false)
    }
  }

  //操作按钮
  const btnArr = [
    { elType: 'button', text: '添加员工', onClick: handleAddAccount }
  ]

  return (
    <>
      <div ref={headerEl}>
        <FormRender {...FormRenderProps} />
      </div>
      <div className='global-page-wrap'>
        <OperaBtnRender style={{ marginBottom: '12px' }} btnArr={btnArr} />
        <TableRender {...TableRenderProps} />
      </div>
      {visible && <EditModal {...EditModalProps} />}
    </>
  )
}

export default AccountComponent;
